﻿using System;
using System.Ext.Xml;
using System.Xml;
using System.Reflection;

namespace mfXmlSerializer
{
    /// <summary>
    /// represents the serialization strategy for classes (nested elements)
    /// </summary>
    public class mfMapClassElement : mfMapBaseElement
    {
        #region CTOR

        public mfMapClassElement(string name)
            : base(name)
        { }

        public mfMapClassElement(mfMapBaseElement baseElement)
            : base(baseElement.Name, baseElement.SetMethod, baseElement.GetMethod, baseElement.ChildMap)
        { }

        #endregion

        #region Methods

        protected override void SerializeElement(XmlWriter xmlWriter, object source)
        {
            this.Check4ChildMap();
            //get child target object
            var childTarget = GetMethod.Invoke(source, null);
            if (childTarget == null)
            {
                return;
            }

            //serialize child map
            ChildMap.SerializeMap(xmlWriter, childTarget);
        }

        protected override void DeserializeElement(XmlReader xmlReader, object target)
        {
            xmlReader.IsElementInvalid(this);
            this.Check4ChildMap();
            //gather child target 
            target = GetMethod.Invoke(target, null);
            ChildMap.DeserializeMap(xmlReader, target);

            xmlReader.AssertIfEndElementIsInvalid(this);
            xmlReader.Read();
        }

        protected override void ExecuteSetElement(object target, string newValue)
        {
            throw new NotImplementedException("executeSet");
        }

        #endregion

    }
}
